import React, { useState, useEffect } from "react";
import { Layout, Menu, Button, Space, Tabs, Input, Tooltip } from "antd";
import type { MenuProps } from "antd";
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  SearchOutlined,
  TableOutlined,
  EyeOutlined,
  FunctionOutlined,
  CodeOutlined,
  SettingOutlined,
  InfoCircleOutlined,
  LockOutlined,
  ToolOutlined,
  DatabaseOutlined,
  ApiOutlined,
} from "@ant-design/icons";
import DatabaseTable from "./components/DatabaseTable";
import DataSourceSider from "./components/DataSourceSider";
import "./App.css";

const { Header, Content, Sider } = Layout;
const { Search } = Input;

type MenuItem = Required<MenuProps>["items"][number];

// 定义菜单项类型
interface MenuItemType {
  key: string;
  label: string;
  children?: MenuItemType[];
}

// 定义数据源类型
interface DataSource {
  id: string;
  name: string;
  type: "mysql" | "postgresql" | "oracle" | "sqlserver";
  icon: React.ReactNode;
}

const App: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false);
  const [selectedRightMenu, setSelectedRightMenu] = useState<string>("objects");
  const [selectedObjectType, setSelectedObjectType] =
    useState<string>("tables");
  const [searchText, setSearchText] = useState<string>("");
  const [filteredObjectItems, setFilteredObjectItems] = useState<MenuItem[]>(
    []
  );
  const [selectedDataSource, setSelectedDataSource] = useState<DataSource>({
    id: "1",
    name: "会计凭证",
    type: "mysql",
    icon: <DatabaseOutlined />,
  });

  // 模拟数据源列表
  const dataSources: DataSource[] = [
    {
      id: "1",
      name: "会计凭证",
      type: "mysql",
      icon: <DatabaseOutlined />,
    },
    {
      id: "2",
      name: "销售系统",
      type: "postgresql",
      icon: <DatabaseOutlined />,
    },
    {
      id: "3",
      name: "人力资源",
      type: "oracle",
      icon: <DatabaseOutlined />,
    },
    {
      id: "4",
      name: "库存管理",
      type: "sqlserver",
      icon: <DatabaseOutlined />,
    },
  ];

  const objectItems: MenuItem[] = [
    {
      key: "tables",
      label: "表",
      icon: <TableOutlined />,
      children: [
        {
          key: "user",
          label: "user",
        },
        {
          key: "dept",
          label: "dept",
        },
        {
          key: "t_user_log_history",
          label: "t_user_log_history",
        },
      ],
    },
    {
      key: "views",
      label: "视图",
      icon: <EyeOutlined />,
      children: [
        {
          key: "v_zwpzk",
          label: "v_zwpzk",
        },
        {
          key: "v_zwpzfl",
          label: "v_zwpzfl",
        },
        {
          key: "v_zwpzys",
          label: "v_zwpzys",
        },
      ],
    },
    {
      key: "functions",
      label: "函数",
      icon: <FunctionOutlined />,
      children: [
        {
          key: "f_get_username",
          label: "f_get_username",
        },
        {
          key: "f_get_deptname",
          label: "f_get_deptname",
        },
      ],
    },
    {
      key: "procedures",
      label: "存储过程",
      icon: <CodeOutlined />,
      children: [
        {
          key: "p_calc_zwpzk",
          label: "p_calc_zwpzk",
        },
        {
          key: "p_register_user",
          label: "p_register_user",
        },
      ],
    },
  ];

  const configItems: MenuItem[] = [
    {
      key: "basic",
      label: "基本信息",
      icon: <InfoCircleOutlined />,
    },
    {
      key: "permissions",
      label: "权限设置",
      icon: <LockOutlined />,
    },
    {
      key: "advanced",
      label: "高级选项",
      icon: <ToolOutlined />,
    },
  ];

  const mainTabs = [
    {
      key: "user",
      label: "表",
      children: <DatabaseTable />,
    },
    {
      key: "data",
      label: "数据",
      children: "数据标签页内容",
    },
    {
      key: "code",
      label: "代码",
      children: "代码标签页内容",
    },
  ];

  const rightMenuItems = [
    {
      key: "objects",
      label: "对象",
      icon: <SettingOutlined />,
    },
    {
      key: "config",
      label: "配置信息",
      icon: <InfoCircleOutlined />,
    },
  ];

  // 根据搜索文本过滤菜单项
  useEffect(() => {
    if (!searchText) {
      setFilteredObjectItems(objectItems);
      return;
    }

    const filterItems = (items: MenuItem[]): MenuItem[] => {
      return items
        .map((item) => {
          if (!item) return null;

          // 将 MenuItem 转换为 MenuItemType
          const menuItem = item as unknown as MenuItemType;
          const label = menuItem.label;
          const children = menuItem.children;

          // 如果当前项匹配搜索文本
          if (label.toLowerCase().includes(searchText.toLowerCase())) {
            return item;
          }

          // 如果有子项，递归过滤
          if (children && children.length > 0) {
            const filteredChildren = filterItems(
              children as unknown as MenuItem[]
            );
            if (filteredChildren.length > 0) {
              return {
                ...item,
                children: filteredChildren,
              };
            }
          }

          return null;
        })
        .filter(Boolean) as MenuItem[];
    };

    setFilteredObjectItems(filterItems(objectItems));
  }, [searchText]);

  // 根据选中的对象类型渲染不同的内容
  const renderContent = () => {
    if (selectedRightMenu === "objects") {
      if (selectedObjectType === "user") {
        return <Tabs items={mainTabs} className="main-tabs" />;
      } else if (selectedObjectType === "dept") {
        return <div className="placeholder-content">部门表内容</div>;
      } else if (selectedObjectType === "t_user_log_history") {
        return <div className="placeholder-content">用户日志历史表内容</div>;
      } else if (selectedObjectType === "v_zwpzk") {
        return <div className="placeholder-content">总账凭证视图内容</div>;
      } else if (selectedObjectType === "v_zwpzfl") {
        return <div className="placeholder-content">总账凭证分类视图内容</div>;
      } else if (selectedObjectType === "v_zwpzys") {
        return <div className="placeholder-content">总账凭证要素视图内容</div>;
      } else if (selectedObjectType === "f_get_username") {
        return <div className="placeholder-content">获取用户名函数内容</div>;
      } else if (selectedObjectType === "f_get_deptname") {
        return <div className="placeholder-content">获取部门名函数内容</div>;
      } else if (selectedObjectType === "p_calc_zwpzk") {
        return (
          <div className="placeholder-content">计算总账凭证存储过程内容</div>
        );
      } else if (selectedObjectType === "p_register_user") {
        return <div className="placeholder-content">注册用户存储过程内容</div>;
      }
      return (
        <div className="placeholder-content">
          请选择具体的{selectedObjectType}
        </div>
      );
    } else {
      if (selectedObjectType === "basic") {
        return <div className="placeholder-content">基本信息配置内容</div>;
      } else if (selectedObjectType === "permissions") {
        return <div className="placeholder-content">权限设置配置内容</div>;
      } else if (selectedObjectType === "advanced") {
        return <div className="placeholder-content">高级选项配置内容</div>;
      }
      return <div className="placeholder-content">配置信息内容</div>;
    }
  };

  const handleSearch = (value: string) => {
    setSearchText(value);
  };

  // 获取数据库类型对应的图标
  const getDatabaseIcon = (type: string) => {
    switch (type) {
      case "mysql":
        return <DatabaseOutlined style={{ color: "#00758F" }} />;
      case "postgresql":
        return <DatabaseOutlined style={{ color: "#336791" }} />;
      case "oracle":
        return <DatabaseOutlined style={{ color: "#C00" }} />;
      case "sqlserver":
        return <DatabaseOutlined style={{ color: "#CC2927" }} />;
      default:
        return <DatabaseOutlined />;
    }
  };

  return (
    <Layout className="app-container">
      <DataSourceSider collapsed={collapsed} />
      <Layout className="right-layout">
        <Header className="header">
          <div className="header-left">
            <Button
              type="text"
              icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              onClick={() => setCollapsed(!collapsed)}
              className="trigger-button"
            />
            <Tooltip
              title={`${
                selectedDataSource.name
              } (${selectedDataSource.type.toUpperCase()})`}
            >
              <div className="database-icon">
                {getDatabaseIcon(selectedDataSource.type)}
              </div>
            </Tooltip>
            <span className="header-title">{selectedDataSource.name}</span>
          </div>
          <Space className="header-actions">
            <Button type="primary">SQL工作室</Button>
            <Button>编辑数据源</Button>
          </Space>
        </Header>
        <Content className="content">
          <div className="content-header">
            <div className="section-title">{selectedDataSource.name}</div>
            <Menu
              mode="horizontal"
              selectedKeys={[selectedRightMenu]}
              items={rightMenuItems}
              className="right-menu"
              onClick={({ key }) => setSelectedRightMenu(key)}
            />
          </div>
          <Layout className="content-layout">
            <Sider theme="light" width={200} className="object-sider">
              {selectedRightMenu === "objects" && (
                <div className="object-search">
                  <Search
                    placeholder="搜索对象"
                    allowClear
                    enterButton={<SearchOutlined />}
                    size="small"
                    onSearch={handleSearch}
                    onChange={(e) => setSearchText(e.target.value)}
                    value={searchText}
                  />
                </div>
              )}
              <Menu
                mode="inline"
                selectedKeys={[selectedObjectType]}
                items={
                  selectedRightMenu === "objects"
                    ? filteredObjectItems
                    : configItems
                }
                className="custom-menu"
                onClick={({ key }) => setSelectedObjectType(key)}
              />
            </Sider>
            <Content className="content-body">{renderContent()}</Content>
          </Layout>
        </Content>
      </Layout>
    </Layout>
  );
};

export default App;
